<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------
namespace api\portal\controller;

use api\common\controller\ApiBaseController;
use api\portal\model\MerchModel;
use cmf\lib\Upload;
use model\GoodsModel;
use think\facade\Db;

class GoodsController extends ApiBaseController
{


    /**
     * 详情
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function detail()
    {
        $goodsModel = new GoodsModel();
        $id = $this->request->get('id');
        if (empty($id)) {
            return $this->error('数据错误');
        }

        $goods = $goodsModel->where(['id' => $id])->find()->toArray();
        $res['goods'] = $goodsModel::decode($goods);
        $res['merch'] = MerchModel::where(['id' => $goods['merch_id']])->field('*')->find();
        return $this->success('成功', $res);
    }


    /**
     * 列表
     * @throws \think\db\exception\DbException
     */
    public function list()
    {
        $goodsModel = new GoodsModel();
        $list = Db::name('goods')->where('is_delete', 0)->paginate(20);
        foreach ($list as &$item) {
            $item = $goodsModel->decode($item);
        }
        return $this->success('成功', $list);
    }


    /**
     * 上传图片
     */
    public function uoloadImage()
    {
        if ($this->request->isPost()) {
            $uploader = new Upload();
            $fileType = $this->request->param('filetype', 'image');
            $uploader->setFileType($fileType);

            $result = $uploader->upload();

            if ($result === false) {
                $this->error($uploader->getError());
            } else {
                $result['preview_url'] = $fileType === 'image' ? cmf_get_image_preview_url($result["filepath"]) : cmf_get_asset_url($result["filepath"]);
                $result['url'] = $fileType === 'image' ? cmf_get_image_url($result["filepath"]) : cmf_get_file_download_url($result["filepath"]);
                $result['filename'] = $result["name"];
                $this->success('上传成功!', $result);
            }
        }
    }


}
